/* 
 * Spinneret - Semi-Structured Database Engine
 * Copyright (c) 2009 Tom Bradford <spinneretdb.org>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a 
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 */

#include <stdlib.h>
#include <string.h>
#include <stdint.h>

#include "utils/mem.h"

/* Private Types and Variables ***********************************************/

#define COUNTED 0x01
#define ATOMIC  0x02
#define LEAKING 0x20
#define MARKED  0x40
#define DELETED 0x80

/** Incomplete type for Block instances */
typedef struct sdb_block_t sdb_block_t;

/** Implementation type for Memory Chain instances */
struct sdb_mem_t {
    sdb_mem_functions_t* functions;    
    sdb_block_t* headBlock;    
    bool clearMemory;
};

/** Implementation type for Block instances */
struct sdb_block_t {
    uint8_t status;
    uint16_t referenceCount;
    
    sdb_mem_t* mem;
    sdb_block_t* prev;
    sdb_block_t* next;
    sdb_ptr_disposal_t* disposalFunction;
    
    size_t size;
    char data[];
};

/** Global root Memory Chain instance */
static sdb_mem_t* memRoot;

/* Private Functions *********************************************************/

static sdb_mem_t* private_getMemRoot(void)
{
    // Default set of Memory Functions
    static sdb_mem_functions_t functions = {
        .mallocFunction = malloc,
        .reallocFunction = realloc,
        .memsetFunction = memset,
        .freeFunction = free
    };

    if ( !memRoot ) {
        memRoot = malloc(sizeof(sdb_mem_t));

        memRoot->functions = &functions;
        memRoot->headBlock = NULL;
        memRoot->clearMemory = false;
    }
    
    return memRoot;
}

/*---------------------------------------------------------------------------*/

static void* private_getPointer(sdb_block_t* block, size_t pos)
{
    return &(block->data[pos]);
}

/*---------------------------------------------------------------------------*/

static sdb_block_t* private_getBlock(void* ptr)
{
    sdb_block_t* block = ptr;
    
    return --block; 
}

/*---------------------------------------------------------------------------*/

static void private_freeBlock(sdb_block_t* block)
{    
    if ( block->status == MARKED || block->status == DELETED )
        return;

    sdb_mem_t* mem = block->mem;

    block->status = MARKED;
    
    // Unlink from the active References
    if ( block->prev )
        block->prev->next = block->next;
        
    if ( block->next )
        block->next->prev = block->prev;
            
    if ( mem->headBlock == block ) 
        mem->headBlock = block->next;
    
    if ( block->disposalFunction ) {
        void* data = private_getPointer(block, 0);    
        block->disposalFunction(data);
    }

    block->status = DELETED;
    mem->functions->freeFunction(block);
}

/*---------------------------------------------------------------------------*/

static void private_dispose(sdb_mem_t* mem)
{
    // This requires two passes, one to mark the block as being in the
    // process of freeing, and another to actually perform the work.
    // The reason for this is that the disposal functions may attempt
    // to access or explicitly free other items in the chain.
    
    // Mark Pass
    sdb_block_t* block = mem->headBlock;
    
    while ( block ) {
        sdb_block_t* nextBlock = block->next;
        block->status = MARKED;
        block = nextBlock;
    }

    // Free Pass
    block = mem->headBlock;
    
    while ( block ) {
        sdb_block_t* nextBlock = block->next;
        
        if ( block->disposalFunction ) {
            void* data = private_getPointer(block, 0);    
            block->disposalFunction(data);
        }
               
        block->status = DELETED; 
        mem->functions->freeFunction(block);
        block = nextBlock;
    }
               
    sdb_ptr_free(mem);
}

/* Public Functions **********************************************************/

sdb_mem_t* sdb_mem_new(sdb_mem_t* parentMem)
{
    if ( !parentMem )
        parentMem = private_getMemRoot();
        
    sdb_mem_t* mem = sdb_mem_malloc(parentMem, sizeof(sdb_mem_t));
    
    mem->headBlock = NULL;
    mem->clearMemory = parentMem->clearMemory;
    mem->functions = parentMem->functions;
    
    sdb_ptr_setDisposalFunction(mem, private_dispose);

    return mem;
}

/*---------------------------------------------------------------------------*/

void* sdb_mem_malloc(sdb_mem_t* mem, size_t size)
{
    size_t fullSize = sizeof(sdb_block_t) + size;
    sdb_block_t* block = mem->functions->mallocFunction(fullSize);

    if ( block ) {
        block->status = 0;
        block->referenceCount = 0;
        block->mem = mem;        
        block->disposalFunction = NULL;            
        block->size = size;
    
        void* data = private_getPointer(block, 0);
        
        if ( mem->clearMemory )
            mem->functions->memsetFunction(data, 0, size);
        
        // Link into the active References
        sdb_block_t* headBlock = mem->headBlock;
            
        if ( headBlock ) {
            headBlock->prev = block;
            block->next = headBlock;
            block->prev = NULL;
            mem->headBlock = block;
        }
        else {        
            block->next = NULL;
            block->prev = NULL;
            mem->headBlock = block;
        }
        
        return data;
    }
    else
        return NULL;
}

/*---------------------------------------------------------------------------*/

void* sdb_mem_calloc(sdb_mem_t* mem, size_t count, size_t size)
{
    return sdb_mem_malloc(mem, count * size);
}

/*---------------------------------------------------------------------------*/

void sdb_mem_setClearMemory(sdb_mem_t* mem, bool clearMemory)
{
    mem->clearMemory = clearMemory;
}

/*---------------------------------------------------------------------------*/

bool sdb_mem_isClearMemory(sdb_mem_t* mem)
{
    return mem->clearMemory;
}

/*---------------------------------------------------------------------------*/

void sdb_mem_setMemoryFunctions(sdb_mem_t* mem,
                                sdb_mem_functions_t* functions)
{
    mem->functions = functions;
}

/*---------------------------------------------------------------------------*/

sdb_mem_functions_t* sdb_mem_getMemoryFunctions(sdb_mem_t* mem)
{
    return mem->functions;
}

/*---------------------------------------------------------------------------*/

void sdb_ptr_setDisposalFunction(void* ptr, 
                                 sdb_ptr_disposal_t* disposalFunction)
{
    sdb_block_t* block = private_getBlock(ptr);
    block->disposalFunction = disposalFunction;
}

/*---------------------------------------------------------------------------*/

sdb_ptr_disposal_t* sdb_ptr_getDisposalFunction(void* ptr)
{
    sdb_block_t* block = private_getBlock(ptr);
    
    return block->disposalFunction;    
}

/*---------------------------------------------------------------------------*/

void* sdb_ptr_retain(void* ptr)
{
    if ( ptr ) {
        sdb_block_t* block = private_getBlock(ptr);
        
        if ( block->referenceCount < UINT16_MAX )  
            block->referenceCount++;
        else
            block->status = LEAKING;
    }
    
    return ptr;
}

/*---------------------------------------------------------------------------*/

void sdb_ptr_release(void* ptr)
{
    if ( ptr ) {
        sdb_block_t* block = private_getBlock(ptr);
        
        if ( block->referenceCount > 1 ) 
            block->referenceCount--;
        else 
            private_freeBlock(block);
    }
}

/*---------------------------------------------------------------------------*/

void* sdb_ptr_realloc(void* ptr, size_t size)
{
    sdb_block_t* block = private_getBlock(ptr);
    
    sdb_mem_t* mem = block->mem;
    bool isHeadBlock = mem->headBlock == block;
    
    block = mem->functions->reallocFunction(block, sizeof(sdb_block_t) + size);
    
    if ( block ) {
        if ( mem->clearMemory && size > block->size ) {
            void* data = private_getPointer(block, block->size);
            mem->functions->memsetFunction(data, 0, size - block->size);
        }
        
        block->size = size;
                 
        if ( block->prev )
            block->prev->next = block;
            
        if ( block->next )
            block->next->prev = block;
            
        if ( isHeadBlock )
            mem->headBlock = block;

        return private_getPointer(block, 0);
    }
    else
        return NULL;    
}

/*---------------------------------------------------------------------------*/

void sdb_ptr_free(void* ptr)
{
    sdb_block_t* block = private_getBlock(ptr);
    private_freeBlock(block);
}

/*---------------------------------------------------------------------------*/

size_t sdb_ptr_getSize(void* ptr)
{
    sdb_block_t* block = private_getBlock(ptr);
    
    return block->size;    
}

/*---------------------------------------------------------------------------*/

sdb_mem_t* sdb_ptr_getMem(void* ptr)
{
    sdb_block_t* block = private_getBlock(ptr);
    
    return block->mem;    
}
